package com.neo33.domain.strategy.service.rule.chain.impl;

import com.neo33.domain.strategy.model.entity.RuleActionEntity;
import com.neo33.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.neo33.domain.strategy.repository.IStrategyRepository;
import com.neo33.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.neo33.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.neo33.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component("rule_whitelist")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class WhiteListLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;

    @Override
    protected String ruleModel() {
        return DefaultChainFactory.LogicModel.RULE_WHITELIST.getCode();
    }

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链-白名单开始 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());
        String[] splitRuleValue = ruleValue.split(Constants.COLON);
        if (splitRuleValue.length == 2) {
            Long awardId = Long.parseLong(splitRuleValue[0]);
            String[] userWhiteIds = splitRuleValue[1].split(Constants.SPLIT);
            for (String userWhiteId : userWhiteIds) {
                if (userId.equals(userWhiteId)) {
                    // 移出该用户
                    List<String> newUserWhiteIdList = Arrays.stream(userWhiteIds)
                            .filter(element -> !element.equals(userId))
                            .collect(Collectors.toList());
                    String newRuleValue = awardId + Constants.COLON + String.join(Constants.SPLIT, newUserWhiteIdList);
                    repository.updateStrategyRuleValue(strategyId, awardId, ruleModel(), newRuleValue);

                    return DefaultChainFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .logicModel(ruleModel())
                            .build();
                }
            }
        }
        // 过滤其他责任链
        log.info("抽奖责任链-白名单放行 userId:{} strategyId:{} ruleModel:{}", userId, strategyId, ruleModel());

        return next().logic(userId, strategyId);
    }
}
